package com.eight.cloud.excel.listener;


import cn.hutool.core.util.ObjectUtil;
import cn.idev.excel.context.AnalysisContext;
import cn.idev.excel.event.AnalysisEventListener;
import com.eight.cloud.core.utils.format.ObjectFormat;
import com.eight.cloud.excel.service.AnalysisAfterService;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * excel监听器
 *
 * @ClassName: ExcelListener
 * @Author: TXC
 * @Date: 2025-08-06 15:22
 **/
@Slf4j
public class ExcelListener<T> extends AnalysisEventListener<T> {

    private final AnalysisAfterService analysisAfterService;
    public ExcelListener(AnalysisAfterService analysisAfterService) {
        this.analysisAfterService = analysisAfterService;
    }
    /**
     * 每隔1000条存储数据库，实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 1000;
    List<T> list = new ArrayList<>();

    @Override
    public void invoke(T data, AnalysisContext context) {
        list.add(data);
        log.info("解析到一条数据:{}", ObjectFormat.objectToStr(data));
        if (ObjectUtil.isNotNull(analysisAfterService)) {
            analysisAfterService.afterAnalysis(context);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        log.info("所有数据解析完成！");
    }


    /**
     * 返回list
     */
    public List<T> getData() {
        return this.list;
    }
}
